from flask import request, jsonify
from flask import request, jsonify, current_app
from . import api_bp

# 从current_app获取db和模型引用
def get_db_and_models():
    db = current_app.db
    Article = current_app.Article
    return db, Article

# 获取文章列表API
@api_bp.route('/articles', methods=['GET'])
def get_articles():
    # 获取db和模型引用
    db, Article = get_db_and_models()
    
    # 获取分页参数
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    # 查询文章列表，按发布日期倒序排列
    pagination = Article.query.order_by(Article.publish_date.desc()).paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    articles = pagination.items
    
    # 格式化文章数据
    result = []
    for article in articles:
        result.append({
            'id': article.id,
            'title': article.title,
            'summary': article.summary,
            'cover_image': article.cover_image,
            'publish_date': article.publish_date
        })
    
    return jsonify({
        'success': True,
        'data': {
            'articles': result,
            'total': pagination.total,
            'page': page,
            'per_page': per_page,
            'has_next': pagination.has_next
        }
    })

# 获取文章详情API
@api_bp.route('/articles/<int:article_id>', methods=['GET'])
def get_article_detail(article_id):
    # 获取db和模型引用
    db, Article = get_db_and_models()
    
    # 查询文章详情
    article = Article.query.get(article_id)
    
    if not article:
        return jsonify({'success': False, 'message': '文章不存在'}), 404
    
    # 格式化文章数据
    result = {
        'id': article.id,
        'title': article.title,
        'summary': article.summary,
        'content': article.content,
        'cover_image': article.cover_image,
        'publish_date': article.publish_date,
        'created_at': article.created_at.strftime('%Y-%m-%d %H:%M:%S'),
        'updated_at': article.updated_at.strftime('%Y-%m-%d %H:%M:%S')
    }
    
    return jsonify({'success': True, 'data': result})

# 创建文章API（管理后台使用）
@api_bp.route('/articles', methods=['POST'])
def create_article():
    # 获取db和模型引用
    db, Article = get_db_and_models()
    
    data = request.json
    
    if not data:
        return jsonify({'success': False, 'message': '缺少文章数据'}), 400
    
    # 检查必要字段
    required_fields = ['title', 'summary', 'content', 'publish_date']
    for field in required_fields:
        if field not in data:
            return jsonify({'success': False, 'message': f'缺少{field}字段'}), 400
    
    # 创建新文章
    new_article = Article(
        title=data['title'],
        summary=data['summary'],
        content=data['content'],
        cover_image=data.get('cover_image'),
        publish_date=data['publish_date']
    )
    
    db.session.add(new_article)
    db.session.commit()
    
    return jsonify({'success': True, 'message': '文章创建成功', 'article_id': new_article.id})

# 更新文章API（管理后台使用）
@api_bp.route('/articles/<int:article_id>', methods=['PUT'])
def update_article(article_id):
    # 获取db和模型引用
    db, Article = get_db_and_models()
    
    data = request.json
    
    if not data:
        return jsonify({'success': False, 'message': '缺少文章数据'}), 400
    
    # 查询文章
    article = Article.query.get(article_id)
    
    if not article:
        return jsonify({'success': False, 'message': '文章不存在'}), 404
    
    # 更新文章信息
    if 'title' in data:
        article.title = data['title']
    if 'summary' in data:
        article.summary = data['summary']
    if 'content' in data:
        article.content = data['content']
    if 'cover_image' in data:
        article.cover_image = data['cover_image']
    if 'publish_date' in data:
        article.publish_date = data['publish_date']
    
    db.session.commit()
    
    return jsonify({'success': True, 'message': '文章更新成功'})

# 删除文章API（管理后台使用）
@api_bp.route('/articles/<int:article_id>', methods=['DELETE'])
def delete_article(article_id):
    # 获取db和模型引用
    db, Article = get_db_and_models()
    
    # 查询文章
    article = Article.query.get(article_id)
    
    if not article:
        return jsonify({'success': False, 'message': '文章不存在'}), 404
    
    # 删除文章
    db.session.delete(article)
    db.session.commit()
    
    return jsonify({'success': True, 'message': '文章删除成功'})